package test01;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class User extends Thread {
    private final File source;
    private final File dest;
    private volatile long copiedBytes = 0; // 实时已拷贝字节数
    private volatile long totalBytes;      // 总字节数

    public User(File source, File dest) {
        this.source = source;
        this.dest = dest;
        this.totalBytes = source.length();
    }

    @Override
    public void run() {
        try (
                InputStream in = Files.newInputStream(source.toPath());
                OutputStream out = Files.newOutputStream(dest.toPath())
        ) {
            byte[] buffer = new byte[4 * 1024]; // 4KB缓冲区
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
                copiedBytes += bytesRead; // 更新已拷贝字节
            }
            System.out.println("文件拷贝成功: " + source + " -> " + dest);
        } catch (IOException e) {
            System.err.println("文件拷贝失败: " + e.getMessage());
        }
    }

    // 获取拷贝进度百分比（0-100）
    public int getProgress() {
        if (totalBytes == 0) return 0;
        return (int) (copiedBytes * 100 / totalBytes);
    }
}